import pandas as pd
import matplotlib.pyplot as plt
import os

def emotion_seven():
    # 读取Excel文件
    file_path = '../public/data/tables/data_emotion_analysis.xlsx'
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"文件路径不存在: {file_path}")

    df = pd.read_excel(file_path)

    # 提取出七个列
    columns_of_interest = ['好', '乐', '哀', '怒', '惧', '恶', '惊']
    for col in columns_of_interest:
        if col not in df.columns:
            raise KeyError(f"列名不存在: {col}")

    df_selected = df[columns_of_interest]

    # 计算每列的总和
    sums = df_selected.sum()

    # 排序
    sums_sorted = sums.sort_values()

    # 设置颜色映射
    norm = plt.Normalize(sums_sorted.min(), sums_sorted.max())
    sm = plt.cm.ScalarMappable(cmap='Blues', norm=norm)
    sm.set_array([])

    # 设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei']

    # 绘制水平直方图
    fig, ax = plt.subplots(figsize=(10, 6))
    bars = ax.barh(sums_sorted.index, sums_sorted.values, color=sm.to_rgba(sums_sorted.values))
    ax.set_xlabel('总数', fontsize=14)
    ax.set_ylabel('情绪', fontsize=14)
    ax.set_title('情绪总数直方图', fontsize=16)

    # 在每个柱子上显示数值
    for bar in bars:
        width = bar.get_width()
        ax.text(width, bar.get_y() + bar.get_height() / 2.0, f'{width}', ha='left', va='center', fontsize=12)

    # 添加颜色条
    cbar = fig.colorbar(sm, ax=ax)
    cbar.set_label('总数')

    # 确保保存图像的目录存在
    output_dir = os.path.dirname('../public/data/img/emotion_seven.png')
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    # 显示图表
    # plt.show()
    plt.savefig('../public/data/img/emotion_seven.png')


